﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class _Default : BasePage
{
    private List<string> list = null;

    private List<string> PathList
    {
        get
        {
            list = (List<string>)Session["PathList"];
            if (list == null)
            {
                list = new List<string>();
                Session.Add("PathList", list);
            }
            return list;
        }
    }

    private int PathIndex
    {
        get { return (int)Session["PathIndex"]; }
        set { Session["PathIndex"] = value; }
    }

    private TreeNode GetTreeNode(TreeNode node, string path)
    {
        TreeNode tempNode = null;
        DirectoryInfo dir = new DirectoryInfo(path);
        dir.GetDirectories().ToList().ForEach(x =>
        {
            tempNode = new TreeNode("<span class='D'>" + x.Name + "</span>", x.Name);
            node.ChildNodes.Add(tempNode);
            GetTreeNode(tempNode, x.FullName);
        });

        return node;
    }

    private void GetFileInfo(string path)
    {
        try
        {
            DirectoryInfo dir = new DirectoryInfo(path);
            List<FileInfo> list = dir.GetFiles().ToList();
            this.GridView1.DataSource = list;
            this.GridView1.DataBind();
            this.TextBoxCurrent.Text = dir.Name;
        }
        catch
        {
            this.GridView1.DataSource = null;
        }
    }

    private void LoadData(string currentPath)
    {
        this.Path.Text = currentPath;
        if (PathList.Contains(currentPath))
        {
            PathIndex = PathList.FindIndex(x => x == currentPath);
        }
        else
        {
            PathIndex = PathList.Count;
            PathList.Add(currentPath);
        }

        try
        {
            DirectoryInfo dir = new DirectoryInfo(currentPath);
            TreeNode root = new TreeNode("<span>" + dir.Name + "<span>", dir.FullName);
            root = GetTreeNode(root, dir.FullName);
            root.Selected = true;

            this.TreeView1.Nodes.Clear();
            this.TreeView1.Nodes.Add(root);
            GetFileInfo(currentPath);
        }
        catch (Exception ex)
        {
            Alert("读取目录出错，错误信息\r\n：" + ex.Message);
        }
    }

    private string GetPath(TreeNode node)
    {
        if (node == null) { return ""; }
        return node.ValuePath.Replace("/", "\\");
    }

    private TreeNode GetNoCheckedParent(TreeNode node)
    {
        if (node.Parent.Checked)
        {
            return GetNoCheckedParent(node.Parent);
        }
        return node.Parent;
    }

    private bool Find(TreeNode node, TreeNodeCollection coll)
    {
        if (coll.Contains(node))
        {
            return true;
        }
        bool flag = false;
        foreach (TreeNode n in coll)
        {
            flag = flag | Find(node, n.ChildNodes);
            if (flag) { return true; }
        }
        return flag;
    }

    #region Event handler.
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            return;
        }

        string currentPath = MapPath("");
        LoadData(currentPath);
    }

    protected void Go_Click(object sender, EventArgs e)
    {
        string currentPath = Path.Text;
        if (Directory.Exists(currentPath))
        {
            LoadData(currentPath);
        }
        else
        {
            Alert("你输入的路径不存在，请重新输入！");
        }
    }

    protected void SelectedNodeChanged(object sender, EventArgs e)
    {
        TreeNode node = this.TreeView1.SelectedNode;
        if (node != null)
        {
            GetFileInfo(GetPath(node));
            node.Expand();
        }
    }

    protected void Up_Click(object sender, EventArgs e)
    {
        string path = Path.Text;
        DirectoryInfo dir = new DirectoryInfo(path);
        if (!dir.Exists)
        {
            Alert("目录不存在，请重新输入！");
            return;
        }
        if (dir.Parent != null)
        {
            LoadData(dir.Parent.FullName);
        }
    }

    protected void Previous_Click(object sender, EventArgs e)
    {
        if (PathIndex > 0)
        {
            int index = PathIndex - 1;
            LoadData(PathList[index]);
        }
    }

    protected void Next_Click(object sender, EventArgs e)
    {
        if (PathIndex < PathList.Count - 1)
        {
            int index = PathIndex + 1;
            LoadData(PathList[index]);
        }
    }

    protected void Upload_Click(object sender, EventArgs e)
    {
        if (!this.FileUpload1.HasFile)
        {
            return;
        }

        string path = GetPath(this.TreeView1.SelectedNode);
        try
        {
            this.FileUpload1.SaveAs(path + "\\" + this.FileUpload1.PostedFile.FileName);
            GetFileInfo(path);
        }
        catch (Exception ex)
        {
            Alert("上传文件出错，请联系管理员！");
        }
    }

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            File.Delete(e.Keys[0].ToString());
            GetFileInfo(GetPath(this.TreeView1.SelectedNode));
        }
        catch (Exception ex)
        {
            Alert("删除文件出错，请联系管理员！");
        }
    }

    protected void ButtonDelFiles_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow row in this.GridView1.Rows)
        {
            ControlCollection collection = row.Controls;
            CheckBox checkBox = collection[0].Controls[1] as CheckBox;
            if (checkBox.Checked)
            {
                HiddenField field = collection[0].Controls[3] as HiddenField;
                File.Delete(field.Value);
            }
        }
        GetFileInfo(GetPath(this.TreeView1.SelectedNode));
    }

    protected void ButtonDelDir_Click(object sender, EventArgs e)
    {
        try
        {
            Directory.Delete(GetPath(this.TreeView1.SelectedNode), true);
            TreeNode selectNode = this.TreeView1.SelectedNode.Parent;

            if (selectNode != null)
            {
                selectNode.ChildNodes.Remove(this.TreeView1.SelectedNode);
                selectNode.Selected = true;
                GetFileInfo(GetPath(selectNode));
            }
            else
            {
                this.TreeView1.Nodes.Remove(this.TreeView1.SelectedNode);
            }
        }
        catch (Exception ex)
        {
            Alert("删除时出错，请联系系统管理员！");
        }
    }

    protected void ButtonCreateDir_Click(object sender, EventArgs e)
    {

    }

    protected void ButtonRename_Click(object sender, EventArgs e)
    {
        if (this.TextBoxNewName.Text != "")
        {
            DirectoryInfo dir = new DirectoryInfo(GetPath(this.TreeView1.SelectedNode));
            string newDir = "";
            string srcDir = dir.FullName;
            if (Request["mode"] == "0")
            {
                newDir = dir.Parent.FullName + "\\" + this.TextBoxNewName.Text;
                try
                {
                    Directory.Move(srcDir, newDir);
                    this.TreeView1.SelectedNode.Value = new DirectoryInfo(newDir).Name;
                    this.TreeView1.SelectedNode.Text = this.TextBoxNewName.Text;
                    this.TextBoxCurrent.Text = this.TextBoxNewName.Text;
                }
                catch (Exception ex)
                {
                    Alert("改名失败，请联系管理员！");
                }
            }
            else
            {
                newDir = dir.FullName + "\\" + this.TextBoxNewName.Text;
                try
                {
                    dir = Directory.CreateDirectory(newDir);
                    this.TreeView1.SelectedNode.ChildNodes.Add(new TreeNode(dir.Name, dir.Name));
                }
                catch (Exception ex)
                {
                    Alert("新建目录失败，请联系管理员！");
                }
            }
        }
    }
    #endregion
}